import { Request, RequestHandler, Response } from "express";
import {
  IGetMachineByIdReq,
  IAddMachineReq,
  IUpdateMachineReq,
  IDeleteMachineReq,
} from "../../models/machine.model";
import * as MachineService from "../services/machine.service";
import fs from "fs";
import { IncomingForm } from "formidable";

/**
 * Get machine records
 *
 * @param req Express Request
 * @param res Express Response
 */
export const getMachines: RequestHandler = async (
  req: Request,
  res: Response
) => {
  try {
    const machines = await MachineService.getMachines();

    res.status(200).json({
      data: machines,
      code: 2000,
    })
  } catch (error) {
    console.error(
      "[machine.controller][getMachines][Error] ",
      typeof error === "object" ? JSON.stringify(error) : error
    );
    res.status(500).json({
      message: "仪器列表获取失败！",
    });
  }
};

/**
 * Get active machine records
 *
 * @param req Express Request
 * @param res Express Response
 */
export const getActiveMachines: RequestHandler = async (
  req: Request,
  res: Response
) => {
  try {
    const machines = await MachineService.getActiveMachines();

    res.status(200).json({
      data: machines,
      code: 2000,
    })
  } catch (error) {
    console.error(
      "[machine.controller][getActiveMachines][Error] ",
      typeof error === "object" ? JSON.stringify(error) : error
    );
    res.status(500).json({
      message: "仪器列表获取失败！",
    });
  }
};

/**
 * Get machine record based on id provided
 *
 * @param req Express Request
 * @param res Express Response
 */
// @ts-ignore
export const getMachineById: RequestHandler = async (
  req: IGetMachineByIdReq,
  res: Response
) => {
  try {
    const machine = await MachineService.getMachineById(req.params.id);

    res.status(200).json({
      data: machine,
      code: 2000,
    })
  } catch (error) {
    console.error(
      "[machine.controller][getMachineById][Error] ",
      typeof error === "object" ? JSON.stringify(error) : error
    );
    res.status(500).json({
      message: "仪器信息获取失败！",
    });
  }
};

/**
 * Inserts a new machine record
 *
 * @param req Express Request
 * @param res Express Response
 */
export const addMachine: RequestHandler = async (
  req: IAddMachineReq,
  res: Response
) => {
  try {
    req.body.createdTime = new Date(Date.now());
    req.body.updatedTime = req.body.createdTime;

    const result = await MachineService.insertMachine(req.body);

    res.status(200).json({
      data: result,
      code: 2000,
    })
  } catch (error) {
    console.error(
      "[machine.controller][addMachine][Error] ",
      typeof error === "object" ? JSON.stringify(error) : error
    );
    if (error.code === "ER_DUP_ENTRY") {
      res.status(500).json({
        message: "仪器名称重复，请重新输入！",
      });
    } else {
      res.status(500).json({
        message: "仪器保存失败！",
      });
    }
  }
};

/**
 * Updates existing machine record
 *
 * @param req Express Request
 * @param res Express Response
 */
// @ts-ignore
export const updateMachineById: RequestHandler = async (
  req: IUpdateMachineReq,
  res: Response
) => {
  try {
    req.body.updatedTime = new Date(Date.now());
    const result = await MachineService.updateMachine({
      ...req.body,
      id: req.params.id,
    });

    res.status(200).json({
      data: result,
      code: 2000,
    })
  } catch (error) {
    console.error(
      "[machine.controller][updateMachineById][Error] ",
      typeof error === "object" ? JSON.stringify(error) : error
    );
    if (error.code === "ER_DUP_ENTRY") {
      res.status(500).json({
        message: "仪器名称重复，请重新输入！",
      });
    } else {
      res.status(500).json({
        message: "仪器更新失败！",
      });
    }
  }
};

/**
 * deletes a machine
 *
 * @param req Express Request
 * @param res Express Response
 */
// @ts-ignore
export const deleteMachineById: RequestHandler = async (
  req: IDeleteMachineReq,
  res: Response
) => {
  try {
    const result = await MachineService.deleteMachine(req.params.id);

    res.status(200).json({
      data: result,
      code: 2000,
    })
  } catch (error) {
    console.error(
      "[machine.controller][deleteMachineById][Error] ",
      typeof error === "object" ? JSON.stringify(error) : error
    );
    res.status(500).json({
      message: "仪器删除失败！",
    });
  }
};

/**
 * upload an image for a machine
 *
 * @param req Express Request
 * @param res Express Response
 */
// @ts-ignore
export const upload: RequestHandler = async (req: any, res: Response) => {
  try {
    console.log(req);
    let info = { status: "0", message: "上传仪器图片成功", srcurl: "" };
    // 初始化处理文件对象
    var form = new IncomingForm();
    form.parse(req, function (error, fields, files) {
      if (error) {
        info.status = "1";
        info.message = "上传仪器图片失败！";
        res.send(info);
      }

      const folderPath = 'public/machine/';
      if (!fs.existsSync(folderPath)) {
        fs.mkdirSync(folderPath);
      }
      const fullName = `${folderPath}${Date.now().toString()}_${files.file[0].originalFilename}`;
      fs.writeFileSync(
        `${fullName}`,
        fs.readFileSync(files.file[0].filepath)
      ); // 存储图片到public静态资源文件夹下
      info.srcurl=fullName;
      res.send(info);
    });
  } catch (error) {
    console.error(
      "[machine.controller][deleteMachineById][Error] ",
      typeof error === "object" ? JSON.stringify(error) : error
    );
    res.status(500).json({
      message: "上传仪器图片失败！",
    });
  }
};
